﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Activities;
using System.Activities.Expressions;
using System.Activities.Presentation.PropertyEditing;
using System.Activities.Statements;
using System.Collections.Generic;
using System.ComponentModel;

namespace Vision.Core.ActivityComponents.Messaging
{
    /// <summary>
    /// 
    /// </summary>
    [Designer(typeof(SendEmailMessageDesigner))]
    public sealed class SendEmailMessage : CodeActivity
    {        
        /// <summary>
        /// 
        /// </summary>
        [DefaultValue(null)]
        public InArgument<string> MailFrom { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [DefaultValue(null)]
        public InArgument<string> MailTo { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [DefaultValue(null)]
        public InArgument<string> MailSubject { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [DefaultValue(null)]
        public InArgument<string> MailBody { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [DefaultValue(false)]
        public InArgument<bool> MailBodyIsHtml { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [DefaultValue(null)]
        public InArgument<string> MailHost { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [DefaultValue(null)]
        public InArgument<Dictionary<string, byte[]>> MailAttachments { get; set; }
                    
        /// <summary>
        /// If your activity returns a value, derive from CodeActivity<TResult>
        /// and return the value from the Execute method.
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(CodeActivityContext context)
        {
            MailMessage mailMessage = new MailMessage(context.GetValue(this.MailFrom), context.GetValue(this.MailTo));
            mailMessage.Subject = context.GetValue(this.MailSubject);
            mailMessage.Body = context.GetValue(this.MailBody);
            
            if (context.GetValue(this.MailBodyIsHtml) == true){
                mailMessage.IsBodyHtml = true;
            }
            
            Dictionary<string, byte[]> attachmentDictionary = context.GetValue(this.MailAttachments);
            if (attachmentDictionary != null){
                foreach (string attachment in attachmentDictionary.Keys){
                    mailMessage.Attachments.Add(new Attachment(new MemoryStream(attachmentDictionary[attachment]), attachment));
                }
            }

            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Host = context.GetValue(this.MailHost);
            smtpClient.Send(mailMessage);                        
        }
    }
}
